import Vue from "vue";
import router from "../router/index";

/**
 * @自定义指令   permission  control
 * @按钮权限控制   v-permission
 * @
 */
// 注册一个全局自定义指令  v-permission="{ action: 'member:reset' }"
Vue.directive("permission", {
  inserted: function (el, binding) {
    const action = binding.value.action; //value为指令的绑定值
    const currentRight = router.currentRoute.meta; //获取当前路由的meta
    // console.log(currentRight, "router");
    if (currentRight) {
      // 寻找是否匹配   是否具有权限
      if (currentRight.indexOf(action) == -1) {
        // 不具备权限
        const type = binding.value.effect;
        if (type === "disabled") {
          // 将按钮禁用
          el.disabled = true;
          el.classList.add("is-disabled");
        } else {
          // 将按钮删除
          el.parentNode.removeChild(el);
        }
      }
    }
  },
});

// 自定义指令 按钮权限控制
// export default {
//     directives: {
//         permission(el, binding) {
//             const permissions = router.currentRoute.meta; //所有权限
//             const needPermission = binding.value; //需要的权限
//             const hasPermission = permissions.includes(needPermission)
//             if (!hasPermission) {
//                 setTimeout(() => {
//                     el.parentNode && el.parentNode.removeChild(el); // 将按钮删除  使用了逻辑与操作符 (&&) 来确保 el.parentNode 在尝试调用 removeChild 方法时是存在的
//                 }, 0)
//             }
//         }
//     }
// }

// import store from '@/store'

/**
 * @param {Array} value
 * @returns {Boolean}
 * @example see @/views/permission/directive.vue
 */
/* export default function checkPermission(value) {
  if (value && value instanceof Array && value.length > 0) {
    const roles = store.getters && store.getters.roles
    const permissionRoles = value

    const hasPermission = roles.some(role => {
      return permissionRoles.includes(role)
    })
    return hasPermission
  } else {
    console.error(`need roles! Like v-permission="['admin','editor']"`)
    return false
  }
} */
